package f3a.timermodule;


import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import f3a.bancohoras.MainActivity;
import f3a.bancohoras.R;
import f3a.bancohoras.TimeManager;
import f3a.clockservice.ClockService;
//import f3a.clockservice.ClockService.LocalBinder;
//import android.widget.Chronometer;
//import f3a.timermodule.TimeManager;
//import android.widget.Chronometer;
//import f3a.timermodule.TimeManager;

public class WorkingTimeCounter extends Activity {
	
	private static String TAG = "WorkingTimerCounter";
	
	private Timer refresh;
	private TimerTask task;
	private Handler handler = new Handler();
	private int refreshPeriod = 1000; //in milliseconds;
	private TimeManager chrono = new TimeManager(0,"milliseconds","up","HH:MM:SS");
	private boolean paused = true;
	
	TextView chronoText;
	Intent clockManager;
	ClockService clockService;
	boolean bound = false;
	IBinder clockServiceBinder;
	Messenger clockServiceMsger;
	
	final Messenger myMessenger = new Messenger(new IncomingHandler());
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.time_counter);
	    MainActivity.activities.add(this);
	    
//	    clockManager = new Intent(this, ClockService.class);
	    chronoText = (TextView) findViewById (R.id.clock);
	    
//	    clockServiceBinder = clockService.onBind(getIntent());
	    
	    if (isMyServiceRunning()){
//	    	bindService(new Intent(this, ClockService.class), clockServiceConnection, Context.BIND_AUTO_CREATE);
	    	doBindService();
//	    	Toast.makeText(this, "Service already runnning", Toast.LENGTH_SHORT);
	    	Log.d(TAG,"Service already running");
	    }
	    else{
//	    	Toast.makeText(this, "New service", Toast.LENGTH_SHORT);
	    	Log.d(TAG,"New Service shall be created");
	    	startService(new Intent(this,ClockService.class));
	    	doBindService();
	    }
	    
	    
	    Log.d("Debug", "Hello timer_counter!!!");
	    initTimer();
//	    Log.d("Debug", "initTimer() finalizado!");
//	    chrono = new TimeManager((long)tempo*60*1000, "seconds", "down", "HH:MM:SS");
//	    Log.d("Debug", "chrono criado!");
//	    chronoText.setText(chrono.toString());
	    chronoText.setText("");
//	    Log.d("Debug", "texto escrito!");
	    if (savedInstanceState == null){
	    	Toast.makeText(this, "NEW Working Time Counter has started",Toast.LENGTH_SHORT).show();
	    }else{
	    	Toast.makeText(this, "Re-NEW Working Time Counter has started",Toast.LENGTH_SHORT).show();
	    }        
	}
    
    
//    private void widgetTest(){
//    	Context context = WorkingTimeCounter.this.getApplicationContext();
//    	
//    	
//    }
    
    @Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onRestoreInstanceState(savedInstanceState);
	}


	@Override
	protected void onSaveInstanceState(Bundle outState) {
		// TODO Auto-generated method stub
		super.onSaveInstanceState(outState);
	}


	
    
//    public void escreveRelogio(){
//    	chronoText.setText(chrono.toString());
//    }
    
    @Override
	public void onStop(){
		super.onStop();
//		chrono.pause();
		stopTimer();
		try {
			unbindService(clockServiceConnection);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	@Override
	public void onDestroy(){
		super.onDestroy();
//		chrono.pause();
		try {
			stopTimer();
			doUnbindService();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
    @Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    getMenuInflater().inflate(R.menu.main, menu);
	    return true;
	}
    
    //    public void escreveRelogio(){
	//    	chronoText.setText(chrono.toString());
	//    }
	    
	    public void chronoStartHandler(View start){
			
	//    		Log.d("Debug","Timer start");
		    	if (paused==true) {
					paused = false;
	//				chrono.start();
					Log.d("Debug","ClockService start call");
//			    	if (!isMyServiceRunning()){
//			    		startService(new Intent(this, ClockService.class));
//			    		bindService(new Intent(this, ClockService.class), clockServiceConnection, Context.BIND_AUTO_CREATE);
//			    	}
//			    	doBindService();
//			    	ClockService.startCounter();
			    	sendMessageSetClockTime((3*60+30)*60*1000);
			    	sendMessageActionRequest(ClockService.MSG_START_COUNTER);
				}
		    		    	
		}


	public void chronoPauseHandler(View pause){
			
				if (paused==false){
					paused = true;
	//				chrono.pause();
					Log.d("Debug","ClockService stop call");
					try {
						if (isMyServiceRunning()){
							sendMessageActionRequest(ClockService.MSG_PAUSE_COUNTER);
//							ClockService.puseCounter();
						}
//						unbindService(clockServiceConnection);
//						stopService(new Intent(this, ClockService.class));
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
				}
				
	    }


	public void chronoStopHandler(View stop) {
			
				if (paused==false){
					paused = true;
	//				chrono.pause();
					Log.d("Debug","ClockService stop call");
					try {
						unbindService(clockServiceConnection);
						stopService(new Intent(this, ClockService.class));
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
	//				chrono.reset();
				}
				
		}

	class IncomingHandler extends Handler {
	        @Override
	        public void handleMessage(Message msg) {
	            switch (msg.what) {
	            case ClockService.MSG_SET_INT_VALUE:
	            	if (!paused){
	            		chrono.setClockTime(msg.arg1);
		                chronoText.setText(chrono.toString());
	            	}
	                break;
	            case ClockService.MSG_SET_STRING_VALUE:
	                String str1 = msg.getData().getString("str1");
	//                chronoText.setText("Str Message: " + str1);
	                break;
	            default:
	                super.handleMessage(msg);
	            }
	        }
	    }

	private ServiceConnection clockServiceConnection = new ServiceConnection(){
			
			@Override
			public void onServiceConnected(ComponentName className, IBinder service) {
	//			LocalBinder binder = (LocalBinder) service;
	//			clockService = binder.getService();
				bound = true;
//				paused = false;
				Log.d("Service Connection", "On");
				clockServiceMsger = new Messenger(service);
				try {
	                Message msg = Message.obtain(null, ClockService.MSG_REGISTER_CLIENT);
	                msg.replyTo = myMessenger;
	                clockServiceMsger.send(msg);
	            } catch (RemoteException e) {
	                // In this case the service has crashed before we could even do anything with it
	            }
			}
	
			@Override
			public void onServiceDisconnected(ComponentName name) {
				bound = false;
				paused = true;
				clockServiceMsger = null;
				Log.d("Service Connection", "Off");
			}
	    	
	    	
	    	
	    };

	private boolean isMyServiceRunning() {
//        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
//        for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
//            if (ClockService.class.getName().equals(service.service.getClassName())) {
//                return true;
//            }
//        }
        if (ClockService.isRunning()){
        	return true;
        }
        return false;
    }
    
    void doBindService() {
    	bindService(new Intent(this, ClockService.class), clockServiceConnection, Context.BIND_AUTO_CREATE);
        bound = true;
//        clockServiceMsger = new Messenger(ClockService.getClockBinder());
//        textStatus.setText("Binding.");
    }
    void doUnbindService() {
        if (bound) {
            // If we have received the service, and hence registered with it, then now is the time to unregister.
            if (clockServiceMsger != null) {
                try {
                    Message msg = Message.obtain(null, ClockService.MSG_UNREGISTER_CLIENT);
                    msg.replyTo = myMessenger;
                    clockServiceMsger.send(msg);
                } catch (RemoteException e) {
                    // There is nothing special we need to do if the service has crashed.
                }
            }
            // Detach our existing connection.
            unbindService(clockServiceConnection);
            bound = false;
//            textStatus.setText("Unbinding.");
        }
    }
    
    private void sendMessageToService(int intvaluetosend) {
        if (bound) {
            if (clockServiceMsger != null) {
                try {
                    Message msg = Message.obtain(null, ClockService.MSG_SET_INT_VALUE, intvaluetosend, 0);
                    msg.replyTo = myMessenger;
                    clockServiceMsger.send(msg);
                } catch (RemoteException e) {
                }
            }
        }
    }
    private void sendMessageSetClockTime(int intvaluetosend) {
        if (bound) {
            if (clockServiceMsger != null) {
                try {
                    Message msg = Message.obtain(null, ClockService.MSG_SET_TIMER_VALUE, intvaluetosend, 0);
                    msg.replyTo = myMessenger;
                    clockServiceMsger.send(msg);
                } catch (RemoteException e) {
                }
            }
        }
    }
    
    private void sendMessageActionRequest(int actionTag) {
        if (bound) {
            if (clockServiceMsger != null) {
                try {
                    Message msg = Message.obtain(null, actionTag);
                    msg.replyTo = myMessenger;
                    clockServiceMsger.send(msg);
                } catch (RemoteException e) {
                }
            }
        }
    }
    
	private void initTimer(){
	//    	Log.d("Debug","Ativando Timer");
	    	refresh = new Timer();
	        task = new TimerTask() {
	            public void run() {
	                    handler.post(new Runnable() {
	                            public void run() {
	//                                Log.d("Debug", "Timer ativado");
	//                                escreveRelogio();
	                            }
	                   });
	            }};
	            refresh.schedule(task, refreshPeriod, refreshPeriod);
	    }


	//    public void escreveRelogio(){
	//    	chronoText.setText(chrono.toString());
	//    }
	    
	    private void stopTimer(){
			task.cancel();
			task = null;
			refresh.cancel();
			refresh = null;
		} 
    
}
